<template>
  <div class="app-msg-container">
    <search-bar class="container" v-model="queryParams" :config="searchs" @search="handleSearch" @searchReset="handleReset" />
    <div class="line"></div>
    <table-page
      width="100%"
      ref="noticeTable"
      class="user-table"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :isIndex="true"
      :isSelection="false"
      :indexFixed="true"
      :total="pages.total"
      :pageSize="pages.pageSize"
      :currentPage="pages.pageNum"
      @sizeChange="handleSizeChange"
      @currentChange="handleCurrentChange"
    >
      <template slot="enable" slot-scope="{ row }">
        <el-switch
          v-model="row.enable"
          active-color="#0076FF"
          inactive-color="#B3B3B3"
          :active-value="true"
          :inactive-value="false"
          @change="changeEnable(row)"
        />
      </template>
      <template #handle>
        <el-button type="primary" class="m_96" v-hasPermi="['CentralControl.NoticeTemplateConfig.Create']" @click="handleAdd">新建消息</el-button>
      </template>
    </table-page>
  </div>
</template>

<script>
import { notification_method_type } from '@/utils/dictOptions'
import { getNoticeList, delNotice, notifyTemplateEnable } from '@/api/message'
import SearchBar from '@/components/SearchBar'
import TablePage from '@/components/TablePage'
export default {
  name: 'MessageList',
  components: {
    SearchBar,
    TablePage,
  },
  data: function () {
    return {
      msgGradeDicts: [],
      msgBusinessDicts: [],
      queryParams: {},
      searchs: [
        {
          prop: 'noticeBusinessType',
          type: 'select',
          placeholder: '通知业务',
        },
        {
          prop: 'messageGrade',
          type: 'select',
          placeholder: '消息等级',
          options: [],
        },
        {
          prop: 'enable',
          type: 'select',
          placeholder: '是否启用',
          options: [
            { label: '是', value: true },
            { label: '否', value: false },
          ],
        },
      ],
      tableData: [],
      tableColumn: [
        {
          label: '通知业务',
          prop: 'noticeBusinessType',
          dicts: [],
        },
        {
          label: '通知名称',
          prop: 'noticeName',
        },
        {
          label: '消息等级',
          prop: 'messageGrade',
          type: 'color',
          colors: [
            {
              value: '1',
              color: '#ee3333',
            },
          ],
          // dicts: this.msgGradeDicts,
        },
        {
          label: '通知方式',
          prop: 'notificationMethod',
          dicts: notification_method_type,
        },
        {
          label: '是否启用',
          prop: 'enable',
          type: 'switch',
          render: true,
          policy: ['CentralControl.NoticeTemplateConfig.DisableOrEnable'],
        },
        {
          label: '操作人',
          prop: 'lastModifier',
        },
        {
          label: '操作时间',
          prop: 'lastModificationTime',
        },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          type: 'button',
          width: 170,
          buttons: [
            {
              label: '查看',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleDetail',
            },
            {
              label: '编辑',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleEdit',
              policy: ['CentralControl.NoticeTemplateConfig.Update'],
            },
            {
              label: '删除',
              type: 'text',
              color: '#ee3333',
              method: 'handleDelete',
              policy: ['CentralControl.NoticeTemplateConfig.Delete'],
            },
          ],
        },
      ],
      pages: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
    }
  },
  created() {
    this.initDicts()
    this.getTableData()
  },
  mounted() {
    // 消息详情
    this.$bus.$on('handleDetail', rows => {
      this.$router.push({ path: `/system/msg/detail/${rows.id}` })
    })
    // 消息详情
    this.$bus.$on('handleEdit', rows => {
      this.$router.push({ path: `/system/msg/edit/${rows.id}` })
    })
    // 删除消息
    this.$bus.$on('handleDelete', rows => {
      this.$confirm(`确认删除名称为" ${rows.noticeName} "的消息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delNotice(rows.id).then(res => {
          if (this.pages.total % this.pages.pageSize === 1) {
            const lastpage = (this.pages.total + this.pages.pageSize - 1) / this.pages.pageSize
            if (this.pages.pageNum == lastpage) {
              this.pages.pageNum = this.pages.pageNum - 1
            }
          }
          this.getTableData()
          this.$message({ type: 'success', message: '删除通知成功!' })
        })
      })
    })
  },
  destroyed() {
    this.$bus.$off('handleDetail')
    this.$bus.$off('handleDelete')
    this.$bus.$off('handleEdit')
  },
  methods: {
    getTableData() {
      const params = {
        SkipCount: ((this.pages.pageNum <= 1 ? 1 : this.pages.pageNum) - 1) * this.pages.pageSize,
        MaxResultCount: this.pages.pageSize,
        ...this.queryParams,
      }
      getNoticeList(params).then(res => {
        this.tableData = res.items.map(item => {
          return {
            ...item,
            lastModifier: item.lastModifier || item.creator,
            lastModificationTime: item.lastModificationTime ?? item.creationTime,
            notificationMethod: item.notificationTemplates.filter(t => t['enable']).map(i => i['notificationMethodType']),
          }
        })
        this.pages.total = res.totalCount
      })
    },
    handleSearch() {
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleReset() {
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleSizeChange(v) {
      this.pages.pageSize = v
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleCurrentChange(v) {
      this.pages.pageNum = v
      this.getTableData()
    },
    handleAdd() {
      this.$router.push({ path: '/system/msg/add' })
    },
    async dictMessageBusiness() {
      const arr = await this.$store.dispatch('dicts/dictMessageBusiness')
      const result = arr.map(item => {
        return { label: item.name, value: item.id }
      })
      return result
    },
    async dictMessageGrade() {
      const arr = await this.$store.dispatch('dicts/dictMessageGrade')
      const result = arr.map(item => {
        return { label: item.name, value: item.id }
      })
      return result
    },
    async initDicts() {
      this.msgGradeDicts = await this.dictMessageGrade()
      this.msgBusinessDicts = await this.dictMessageBusiness()
      this.$set(
        this.searchs.find(i => i.prop == 'messageGrade'),
        'options',
        this.msgGradeDicts
      )
      this.$set(
        this.tableColumn.find(i => i.prop == 'messageGrade'),
        'dicts',
        this.msgGradeDicts
      )
      this.$set(
        this.searchs.find(i => i.prop == 'noticeBusinessType'),
        'options',
        this.msgBusinessDicts
      )
      this.$set(
        this.tableColumn.find(i => i.prop == 'noticeBusinessType'),
        'dicts',
        this.msgBusinessDicts
      )
    },
    changeEnable(row) {
      notifyTemplateEnable({ id: row.id, enable: row.enable })
        .then(res => {
          this.$message.success('操作成功!')
          this.getTableData()
        })
        .catch(error => {
          this.tableData.forEach(item => {
            if (item.id == row.id) item.enable = !row.enable
          })
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 17px 30px;
  box-sizing: border-box;
}
.line {
  height: 20px;
  background: $app-main-bgc;
}
</style>
